<template>
  <div>
    <el-tabs v-model="questiontype" >
      <el-tab-pane label="OJ比赛" :name="QuestionType.OJ"></el-tab-pane>
      <el-tab-pane
        v-if="!tenant_id"
        label="公开测"
        :name="QuestionType.PUBLIC_TEST"
      ></el-tab-pane>
      <el-form inline label-width="auto">
        <el-form-item label="比赛名称">
          <el-input
            placeholder="请输入内容"
            @click="start"
            v-model.lazy.trim="like"
            clearable
            style="width: 400px"
          >
            <template #append>
              <el-button @click="start">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <router-link
            :to="{ name: '添加比赛', query: { questiontype } }"
            v-slot="{ navigate }"
            custom
          >
            <el-button @click="navigate" type="primary">+ 添加比赛</el-button>
          </router-link>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        height="74vh"
        border
        style="width: 100%"
        @sort-change="sortchange"
      >
        <el-table-column
          prop="ID"
          sortable
          label="id"
          width="80"
        ></el-table-column>
        <el-table-column prop="userid" sortable label="创建者" width="120">
          <template #default="scope">
            {{ scope.row.user?.name }}
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          sortable
          label="比赛名称"
          width=""
        ></el-table-column>
        <el-table-column label="参与人" width="">
          <template #default="scope">
            <span v-if="scope.row.teamid">
              {{ scope.row.team?.name }}
            </span>
            <span v-else-if="scope.row.type === 'public'"> 公开比赛 </span>
            <span v-else>
              {{ scope.row.activityuser.map((e:any) => e.user.name).join(",") }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="activitystarttime"
          width="200"
          sortable
          label="比赛时间"
        >
          <template #default="scope">
            {{ TimeYH1(scope.row.activitystarttime) }}-{{
              TimeYH1(scope.row.activityendtime)
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="matchuserquestioncount"
          label="比赛状态"
          width="100"
        >
          <template #default="scope">
            <span :class="activitytype(scope.row)">{{
              activitytype(scope.row)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="matchuserquestioncount"
          label="提交人数"
          width="90"
        ></el-table-column>
        <el-table-column
          label="操作"
          :width="questiontype == QuestionType.PUBLIC_TEST ? 350 : 280"
        >
          <template #default="scope">
            <el-button-group>
              <!-- 新增：比赛地址按钮，仅公开测（questiontype=1）显示 -->
              <el-popover
                v-if="scope.row.questiontype == QuestionType.PUBLIC_TEST"
                placement="top"
                :width="320"
                trigger="click"
              >
                <div style="word-break: break-all">
                  <div>
                    <el-button
                      size="default"
                      @click="copyMatchUrl(scope.row.ID)"
                      >复制地址</el-button
                    >
                    <br />
                    <el-link
                      :underline="false"
                      type="primary"
                      :href="matchUrl(scope.row.ID)"
                      target="_blank"
                      >{{ matchUrl(scope.row.ID) }}</el-link
                    >
                  </div>
                  <div
                    v-if="qrcodeMap[scope.row.ID]"
                    style="text-align: center"
                  >
                    <img
                      :src="qrcodeMap[scope.row.ID]"
                      alt="二维码"
                      style="width: 120px; height: 120px; cursor: pointer"
                      @click="previewQrcode(qrcodeMap[scope.row.ID])"
                    />
                  </div>
                </div>
                <template #reference>
                  <el-button
                    type="primary"
                    plain
                    @click.stop="showPopover(scope.row.ID)"
                    >比赛地址</el-button
                  >
                </template>
              </el-popover>
              <router-link
                :to="{
                  name: '添加比赛',
                  query: { ID: scope.row.ID, questiontype },
                }"
                custom
                v-slot="{ navigate }"
              >
                <el-button plain type="warning" @click.stop="navigate"
                  >编辑</el-button
                >
              </router-link>
              <el-button @click.stop="copy(scope.row.ID)" type="info"
                >复制</el-button
              >
              <el-button @click.stop="del(scope.row.ID)" type="danger"
                >删除</el-button
              >
              <el-button
                @click.stop="
                  $router.push({
                    name: '查看比赛',
                    params: { ID: scope.row.ID },
                  })
                "
                type="primary"
                >详情</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pager"
        @current-change="handleCurrentChange"
        :page-size="Number(formquery._limit)"
        layout="total,prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </el-tabs>
    <el-dialog
      v-model="qrcodeDialogVisible"
      width="350px"
      title="二维码预览"
      align-center
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          二维码预览
        </span>
      </template>
      <img
        :src="qrcodeDialogImg"
        alt="二维码大图"
        style="width: 300px; height: 300px; display: block; margin: auto"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import QRCode from "qrcode";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncadmincopyactivity,
  asyncadmindelactivity,
  Iobj,
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { hterobotDomain, QuestionType, testHostname } from "../../../util/data";
import { TimeYH1 } from "../../../util/time";

// 码客行
const tenant_id = inject<string | undefined>('tenant_id', undefined);

const route = useRoute();
const router = useRouter();
const store = useStore(Storekey);
const datenow = computed(() => {
  return store.state.time;
});

const ID = ref();
const formquery = reactive<Iobj<Studycodemodel.Iactivity>>({
  tenant_id,
  _limit: 20,
  _offset: 0,
  _order: "ID",
  questiontype: undefined
});
const questiontype = ref<QuestionType>(QuestionType.OJ); // 默认选中 "OJ比赛"


const tableData = computed(() => {
  return store.state.activity?.rows || [];
});
const count = computed(() => {
  return store.state.activity?.count || 0;
});

watch(formquery, start);

onMounted(() => {
  start();
});

const like = ref();

async function start() {
  try {
    const t: Iobj<Studycodemodel.Iactivity> = {};
    if (like.value) {
      t._like = ["name", like.value];
    }
    store.dispatch("actionactivity", Object.assign(t, formquery));
  } catch (e: any) {
    ElMessage.error(e);
  }
}

function handleCurrentChange(val: number) {
  formquery._offset = Number(formquery._limit) * (val - 1);
}

function sortchange(row: any) {
  const { prop, order } = row;
  if (order == "descending") {
    formquery._sortable = "DESC";
  } else {
    formquery._sortable = "ASC";
  }
  if (prop) {
    formquery._order = prop;
  }
}

function copy(ID: string) {
  try {
    ElMessageBox.confirm("是否复制比赛, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await asyncadmincopyactivity({ ID });
        ElMessage({
          type: "success",
          message: "复制成功!",
        });
        start();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消复制",
        });
      });
  } catch (e: any) {
    ElMessage({
      message: "复制失败" + e,
      type: "error",
    });
  }
}

function del(ID: string) {
  try {
    ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await asyncadmindelactivity({ ID });
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        start();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      });
  } catch (e: any) {
    ElMessage({
      message: "删除失败" + e,
      type: "error",
    });
  }
}

function activitytype(activity: Studycodemodel.Iactivity) {
  const no = Date.now();
  const start = new Date(String(activity.activitystarttime)).getTime();
  const end = new Date(String(activity.activityendtime)).getTime();
  if (no < start) return "未开始";
  if (no < end) return "进行中";
  if (no > end) return "已完成";
}

onMounted(() => {
  // start()
  // 通过路由获取 questiontype 的值并设置到 questiontype 中
  const questiontypeFromRoute = Number(
    route.query?.questiontype
  ) as QuestionType;
  if (questiontypeFromRoute) {
    questiontype.value = questiontypeFromRoute;
  }
  setQuestiontype(questiontype.value);
});

watch(questiontype, (newVal) => {
  setQuestiontype(newVal);
});

// 同步questiontype
function setQuestiontype(newVal: QuestionType) {
  const query = { ...route.query, questiontype: newVal };
  formquery.questiontype = Number(newVal);
  router.replace({ query });
}

// 比赛地址弹窗显示控制
const popoverVisibleMap = ref<Record<number, boolean>>({});

// 比赛二维码缓存
const qrcodeMap = ref<Record<number, string>>({});

// 生成比赛地址
function matchUrl(id: number | string) {
  // 比赛类型不同、url的路由不一样
  // const hash = `#/activity/${id}`;
  //  const hash = `#/home?activityId=${id}`;
  // 判断正式打包环境
  if (process.env.NODE_ENV === "production") {
    // 判断是否是测试环境地址
    if (window.location.hostname === testHostname) {
      return `https://${testHostname}/mathH5#/home?activityId=${id}`;
    } else {
      return `https://${hterobotDomain}/mathH5#/home?activityId=${id}`;
    }
  }
  return `${window.location.origin}/mathH5.html#/home?activityId=${id}`;
}

// 显示popover
function showPopover(id: number) {
  popoverVisibleMap.value = { ...popoverVisibleMap.value, [id]: true };
  // 默认生成二维码
  if (!qrcodeMap.value[id]) {
    genQrcode(id);
  }
}

// 复制比赛地址
function copyMatchUrl(id: number) {
  const url = matchUrl(id);
  if (navigator.clipboard) {
    navigator.clipboard.writeText(url).then(() => {
      ElMessage.success("已复制比赛地址");
    });
  } else {
    // fallback
    const input = document.createElement("input");
    input.value = url;
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
    ElMessage.success("已复制比赛地址");
  }
}

// 生成二维码
function genQrcode(id: number) {
  const url = matchUrl(id);
  QRCode.toDataURL(url, { width: 200 }, (err, dataUrl) => {
    if (!err) {
      qrcodeMap.value = { ...qrcodeMap.value, [id]: dataUrl };
    } else {
      ElMessage.error("二维码生成失败");
    }
  });
}

// 预览二维码大图
function previewQrcode(img: string) {
  qrcodeDialogImg.value = img;
  qrcodeDialogVisible.value = true;
}

const qrcodeDialogVisible = ref(false);
const qrcodeDialogImg = ref("");
</script>

<style scoped>
.upload .el-upload-dragger {
  width: 160px;
  height: 160px;
}

.未开始 {
  color: var(--bs-gray-500);
}

.进行中 {
  color: var(--bs-primary-text);
}

.已完成 {
  color: var(--bs-success);
}
</style>
